<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Infotech Ltd.
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: vshoor $ ($Date: 2007/03/22 11:30:51 $)
// $RCSfile: admin_parser.php,v $ : $Revision: 1.23 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================

if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

if (!$staffauth->isAdmin()) {
	trigger_error("You do not have permission to access $PHP_SELF", E_USER_ERROR);
}

require_once ("./modules/parser/functions_parser.php");
require_once ("./includes/functions_html.php");
$template->loadLanguageSection("emailparser");

/**
* ###############################################
* FUNCTION DECLARATIONS
* ###############################################
*/

/**
* Callback for parsing queue data
*/
function _queueFields($arg)
{
	global $_SWIFT;
	$record = &$arg[0];
	$fields = &$arg[1];

	$record["emailqueues.email"] = '<table width="100%"  border="0" cellspacing="0" cellpadding="1"><tr><td width="1"><img src="'. $_SWIFT["themepath"] .'icon_msgsmallyellow.gif" border="0" /></td><td><span class="smalltext">&nbsp;<a href="index.php?_m=parser&_a=editemailqueue&emailqueueid='. $record["emailqueueid"] .'">'. htmlspecialchars($record["email"]) .'</a></span></td></tr></table>';

	$record["emailqueues.fetchtype"] = $_SWIFT["language"]["fetch".$record["fetchtype"]];
	$record["emailqueues.departmentid"] = $_SWIFT["departmentcache"][$record["departmentid"]]["title"];
	$record["emailqueues.registrationrequired"] = iif($record["registrationrequired"]=="1", $_SWIFT["language"]["yes"], $_SWIFT["language"]["no"]);

	$record["options"] = '<a href="index.php?_m=parser&_a=editemailqueue&emailqueueid='. $record["emailqueueid"] .'" title="'. $_SWIFT["language"]["edit"] .'"><img src="'. $_SWIFT["themepath"] .'icon_edit.gif" border="0">&nbsp;'. $_SWIFT["language"]["edit"] .'</a>&nbsp;&nbsp;&nbsp;&nbsp;<a onClick="javascript:doConfirm(\''. $_SWIFT["language"]["actionconfirm"] .'\', \'index.php?_m=parser&_a=manageemailqueues&do=delete&emailqueueid='. $record["emailqueueid"] .'\');" href="#" title="'. $_SWIFT["language"]["delete"] .'"><img src="'. $_SWIFT["themepath"] .'icon_delete.gif" border="0">&nbsp;'. $_SWIFT["language"]["delete"] .'</a>&nbsp;';
	return $record;
}

/**
* Callback for parsing parser log data
*/
function _parserLogFields($arg)
{
	global $_SWIFT;
	$record = &$arg[0];
	$fields = &$arg[1];

	$record["parserlogs.subject"] = '<a href="javascript:popupDataWindow(\'index.php?_m=parser&_a=viewparserlog&parserlogid='. urlencode($record["parserlogid"]) .'\');">'.sprintf($_SWIFT["language"]["emailsubresultformat"], htmlspecialchars($record["subject"]), htmlspecialchars($record["description"])).'</a>';
	$record["parserlogs.parsetimetaken"] = number_format($record["parsetimetaken"], 3)."&nbsp;".$_SWIFT["language"]["seconds"];
	$record["parserlogs.logtype"] = iif($record["logtype"]=="success", '<img src="'. $_SWIFT["themepath"] .'icon_success.gif" border="0" align="absmiddle" />&nbsp;'.$_SWIFT["language"]["success"], '<img src="'. $_SWIFT["themepath"] .'icon_failure.gif" border="0" align="absmiddle" />&nbsp;'.$_SWIFT["language"]["failure"]);

	$record["parserlogs.dateline"] = edate($_SWIFT["settings"]["dt_datetimeformat"], $record["dateline"]);

	$record["options"] = '<a onClick="javascript:doConfirm(\''. $_SWIFT["language"]["actionconfirm"] .'\', \'index.php?_m=parser&_a=parserlog&do=delete&parserlogid='. $record["parserlogid"] .'\');" href="#" title="'. $_SWIFT["language"]["delete"] .'"><img src="'. $_SWIFT["themepath"] .'icon_delete.gif" border="0">&nbsp;'. $_SWIFT["language"]["delete"] .'</a>&nbsp;';
	return $record;
}

/**
* Callback for breaklines
*/
function _breaklineFields($arg)
{
	global $_SWIFT;
	$record = &$arg[0];
	$fields = &$arg[1];

	$record["breakline"] = '<table width="100%"  border="0" cellspacing="0" cellpadding="1"><tr><td width="1"><img src="'. $_SWIFT["themepath"] .'icon_repair.gif" border="0" /></td><td><span class="smalltext">&nbsp;'. htmlspecialchars($record["breakline"]) .'</span></td></tr></table>';

	$record["options"] = '<a onClick="javascript:doConfirm(\''. $_SWIFT["language"]["actionconfirm"] .'\', \'index.php?_m=parser&_a=managebreaklines&deletebreakline=1&breaklineid='. $record["breaklineid"] .'\');" href="#" title="'. $_SWIFT["language"]["delete"] .'"><img src="'. $_SWIFT["themepath"] .'icon_delete.gif" border="0">&nbsp;'. $_SWIFT["language"]["delete"] .'</a>&nbsp;';
	
	return $record;
}

/**
* Mass Action: Delete Queues
*/
function _maDeleteQueues()
{
	global $_SWIFT;

	if (!is_array($_POST["itemid"]) || $_SWIFT["isdemo"] == true)
	{
		return false;
	}

	deleteQueues($_POST["itemid"]);
}

/**
* Mass Action: Delete Breaklines
*/
function _maDeleteBreaklines()
{
	global $_SWIFT;

	if (!is_array($_POST["itemid"]) || $_SWIFT["isdemo"] == true)
	{
		return false;
	}

	deleteBreaklines($_POST["itemid"]);
}

/**
* Mass Action: Delete Parser Logs
*/
function _maDeleteParserlog()
{
	global $_SWIFT;

	if (!is_array($_POST["itemid"]) || $_SWIFT["isdemo"] == true)
	{
		return false;
	}

	deleteParserLogs($_POST["itemid"]);
}







/**
* ###############################################
* INSERT NEW EMAIL QUEUE
* ###############################################
*/
if ($eventaction == "insertemailqueue")
{
	if ($_POST["step"] == "1" && (trim($_POST["email"]) == ""))
	{
		$errormessage = $_SWIFT["language"]["requiredfieldempty"];
		$_POST["step"] = "";
	} else if ($_POST["step"] == "1" && $_POST["fetchtype"] != "pipe" && (trim($_POST["host"]) == "" || trim($_POST["port"]) == "" || trim($_POST["username"]) == "" || trim($_POST["host"]) == "")) {
		$errormessage = $_SWIFT["language"]["requiredfieldempty"];
		$_POST["step"] = "";
	} else if ($_POST["step"] == 1 && (!empty($_POST["prefix"]) && !ereg('^[[:alnum:]]+$', $_POST["prefix"]))) {
		$errormessage = $_SWIFT["language"]["invalidqueueprefix"];
		$_POST["step"] = "";
	} else if ($_POST["step"] == 1 && ($_SWIFT["isdemo"] == true)) {
		$errormessage = $_SWIFT["language"]["demomode"];
		$_POST["step"] = "";
	} else if ($_POST["step"] == "2") {
		// Wee! We finally get to insert the queue! /me does the happy dance
		$emailqueueid = insertQueue(strtolower($_POST["email"]), $_POST["tgroupid"], $_POST["departmentid"], $_POST["priorityid"], $_POST["ticketstatusid"], iif($_POST["type"]==MODULE_BUGS, MODULE_BUGS, MODULE_TICKETS), $_POST["fetchtype"], $_POST["host"], $_POST["port"], $_POST["username"], $_POST["password"], $_POST["customfromname"], $_POST["customfromemail"], $_POST["signature"], iif($_POST["registrationrequired"]==1, true, false), iif($_POST["issueautoresponder"]==1, true, false), iif($_POST["replyautoresponder"]==1, true, false), $_POST["prefix"]);

		if (!$emailqueueid)
		{
			$errormessage = $_SWIFT["language"]["failedtocreatequeue"];
			$_POST["step"] = "1";
		} else {
			printRedirect($_SWIFT["language"]["redirect_queueinsert"], "index.php?_m=parser&_a=manageemailqueues&insertqueueid=".$emailqueueid);

			exit;
		}
	}

	$interface->adminHeader($_SWIFT["language"]["mailparser"]." > ".$_SWIFT["language"]["insertemailqueue"], 1);

	$interface->adminNavBar('<a href="index.php?_m=parser&_a=manageemailqueues" title="'.$_SWIFT["language"]["mailparser"].'">'.$_SWIFT["language"]["mailparser"].'</a> &raquo; <a href="index.php?_m=parser&_a=insertemailqueue" title="'.$_SWIFT["language"]["insertqueue"].'">'.$_SWIFT["language"]["insertqueue"].'</a>', $_SWIFT["language"]["desc_mailparser"] , 4);

	printInfoBox($infomessage);
	printErrorBox($errormessage);

	printFormStart("queueform");

	/**
	* SPECIFY DEPARTMENT, BUG SEVERITY IF BUGS IS SELECTED.. OTHERWISE IF TICKETS IS SELECTED THEN DISPLAY DEPARTMENTS, PRIORITY, STATUS.
	*/
	if ($_POST["step"] == "1" && $_POST["type"] == "tickets")
	{
		printMainTableHeader($_SWIFT["language"]["queuedetails"]);
		
		printDescRow($_SWIFT["language"]["ticketfields"]);
		// departments
		$options = array();
		$index = 0;
		foreach ($_SWIFT["departmentcache"] as $key=>$val)
		{
			if ($val["departmentmodule"] == "tickets")
			{
				$options[$index]["title"] = $val["title"];
				$options[$index]["value"] = $val["departmentid"];
				$index++;
			}
		}
		printSelectRow("departmentid", $_SWIFT["language"]["queuedepartment"], $_SWIFT["language"]["desc_queuedepartment"], $options);

		// status
		$options = array();
		$index = 0;
		foreach ($_SWIFT["statuscache"] as $key=>$val)
		{
			$options[$index]["title"] = $val["title"];
			$options[$index]["value"] = $val["ticketstatusid"];
			$index++;
		}
		printSelectRow("ticketstatusid", $_SWIFT["language"]["queueticketstatus"], $_SWIFT["language"]["desc_queueticketstatus"], $options);

		// priority
		$options = array();
		$index = 0;
		foreach ($_SWIFT["prioritycache"] as $key=>$val)
		{
			$options[$index]["title"] = $val["title"];
			$options[$index]["value"] = $val["priorityid"];
			$index++;
		}
		printSelectRow("priorityid", $_SWIFT["language"]["queuepriority"], $_SWIFT["language"]["desc_queuepriority"], $options);

		printSubmitRow($_SWIFT["language"]["insertqueue"]);
		printMainTableFooter();

		addHiddenField("step", "2");
		addHiddenField("email", $_POST["email"]);
		addHiddenField("type", $_POST["type"]);
		addHiddenField("fetchtype", $_POST["fetchtype"]);
		addHiddenField("host", $_POST["host"]);
		addHiddenField("port", $_POST["port"]);
		addHiddenField("username", $_POST["username"]);
		addHiddenField("password", $_POST["password"]);
		addHiddenField("customfromname", $_POST["customfromname"]);
		addHiddenField("customfromemail", $_POST["customfromemail"]);
		addHiddenField("signature", $_POST["signature"]);
		addHiddenField("issueautoresponder", $_POST["issueautoresponder"]);
		addHiddenField("replyautoresponder", $_POST["replyautoresponder"]);
		addHiddenField("registrationrequired", $_POST["registrationrequired"]);
		addHiddenField("tgroupid", $_POST["tgroupid"]);
		addHiddenField("prefix", $_POST["prefix"]);
	} else if ($_POST["step"] == "2" && $_POST["type"] == "bugs") {
		
	} else {
		printMainTableHeader($_SWIFT["language"]["queuedetails"]);
		
		printDescRow($_SWIFT["language"]["emailgeneralfields"]);
		printTextRow("email", $_SWIFT["language"]["emailaddress"], $_SWIFT["language"]["desc_emailaddress"], "text", $_POST["email"]);
		
		$options = array();
		$options[0]["title"] = $_SWIFT["language"]["module_tickets"];
		$options[0]["value"] = MODULE_TICKETS;

		// Display only if bug tracking module is registered
		if ($module->isRegistered(MODULE_BUGS))
		{
			$options[1]["title"] = $_SWIFT["language"]["module_bugs"];
			$options[1]["value"] = MODULE_BUGS;
		}
		printSelectRow("type", $_SWIFT["language"]["emailtype"], $_SWIFT["language"]["desc_emailtype"], $options);

		$options = array();
		$options[0]["title"] = $_SWIFT["language"]["fetchpipe"];
		$options[0]["value"] = "pipe";
		$options[0]["selected"] = true;
		$options[1]["title"] = $_SWIFT["language"]["fetchpop3"];
		$options[1]["value"] = "pop3";
		$options[2]["title"] = $_SWIFT["language"]["fetchpop3ssl"];
		$options[2]["value"] = "pop3ssl";
		$options[3]["title"] = $_SWIFT["language"]["fetchimap"];
		$options[3]["value"] = "imap";
		$options[4]["title"] = $_SWIFT["language"]["fetchimapssl"];
		$options[4]["value"] = "imapssl";
		printSelectRow("fetchtype", $_SWIFT["language"]["emailfetchtype"], $_SWIFT["language"]["desc_emailfetchtype"], $options, "switchFields(this.value);");


		$_options = array();
		$index = 0;
		$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."templategroups` ORDER BY `tgroupid` ASC;");
		while ($dbCore->nextRecord())
		{
			$_options[$index]["title"] = $dbCore->Record["title"];
			$_options[$index]["value"] = $dbCore->Record["tgroupid"];
			if (($_POST["tgroupid"] == $dbCore->Record["tgroupid"] && $type == EDIT) || ($dbCore->Record["isdefault"] == 1 && $type == INSERT))
			{
				$_options[$index]["selected"] = true;
			}
			$index++;
		}
		printSelectRow("tgroupid", $_SWIFT["language"]["templategroup"], $_SWIFT["language"]["desc_templategroup"], $_options);

		printDescRow($_SWIFT["language"]["emailimapfields"]);
		printTextRow("host", $_SWIFT["language"]["emailhost"], $_SWIFT["language"]["desc_emailhost"], "text", $_POST["host"]);
		printTextRow("port", $_SWIFT["language"]["emailport"], $_SWIFT["language"]["desc_emailport"], "text", $_POST["port"], "5");
		printTextRow("username", $_SWIFT["language"]["emailusername"], $_SWIFT["language"]["desc_emailusername"], "text", $_POST["username"], "20");
		printTextRow("password", $_SWIFT["language"]["emailpassword"], $_SWIFT["language"]["desc_emailpassword"], "password", $_POST["password"], "20");
		?>
		<script language="Javascript">
			if (document.queueform.fetchtype.value == "pipe")
			{
				switchFields("pipe");				
			}

			function switchFields(fieldtype)
			{
				if (fieldtype == "pipe")
				{
					document.queueform.host.value = "";
					document.queueform.port.value = "";
					document.queueform.username.value = "";
					document.queueform.password.value = "";

					disableField(document.queueform.host);
					disableField(document.queueform.port);
					disableField(document.queueform.username);
					disableField(document.queueform.password);
				} else {
					enableField(document.queueform.host);
					enableField(document.queueform.port);
					enableField(document.queueform.username);
					enableField(document.queueform.password);
				}

				if (fieldtype == "pop3")
				{
					document.queueform.port.value = "110";
				} else if (fieldtype == "imap") {
					document.queueform.port.value = "143";
				} else if (fieldtype == "pop3ssl") {
					document.queueform.port.value = "995";
				} else if (fieldtype == "imapssl") {
					document.queueform.port.value = "993";
				}
				
				
				
			}
		</script>
		<?

		printDescRow($_SWIFT["language"]["queueoverrides"]);
		printTextRow("customfromname", $_SWIFT["language"]["queuefromname"], $_SWIFT["language"]["desc_queuefromname"], "text", $_POST["customfromname"]);
		printTextRow("customfromemail", $_SWIFT["language"]["queuefromemail"], $_SWIFT["language"]["desc_queuefromemail"], "text", $_POST["customfromemail"]);

		printDescRow($_SWIFT["language"]["queuesettings"]);

		printTextRow("prefix", $_SWIFT["language"]["queueprefix"], $_SWIFT["language"]["desc_queueprefix"], "text", $_POST["prefix"]);
		printTextareaRow("signature", $_SWIFT["language"]["queuesignature"], $_SWIFT["language"]["desc_queuesignature"], $_POST["signature"], "50");
		printYesNoRow("registrationrequired", $_SWIFT["language"]["registrationrequired"], $_SWIFT["language"]["desc_registrationrequired"], false);
		printYesNoRow("issueautoresponder", $_SWIFT["language"]["issueautoresponder"], $_SWIFT["language"]["desc_issueautoresponder"], true);
//		printYesNoRow("replyautoresponder", $_SWIFT["language"]["replyautoresponder"], $_SWIFT["language"]["desc_replyautoresponder"], false);

		printSubmitRow($_SWIFT["language"]["queuenextstep"]);

		printMainTableFooter();

		addHiddenField("step", "1");
		$template->assign("backurl", "index.php?_m=parser&_a=manageemailqueues");
	}

	addHiddenField("_m", "parser");
	addHiddenField("_a", "insertemailqueue");
	printFormEnd();

	$interface->adminFooter();










/**
* ###############################################
* EDIT EMAIL QUEUE
* ###############################################
*/
} else if ($eventaction == "editemailqueue") {
	$_emailqueue = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."emailqueues` AS emailqueues LEFT JOIN `". TABLE_PREFIX ."queuesignatures` AS queuesignatures ON (emailqueues.emailqueueid = queuesignatures.emailqueueid) WHERE emailqueues.emailqueueid = '". intval($_REQUEST["emailqueueid"]) ."';");
	if (empty($_emailqueue["emailqueueid"]))
	{
		trigger_error($_SWIFT["language"]["invalidemailqueue"], E_USER_ERROR);
	}

	if ($_POST["step"] == "1") {
		if (trim($_POST["email"]) == "")
		{
			$errormessage = $_SWIFT["language"]["requiredfieldempty"];
		} else if ($_POST["fetchtype"] != "pipe" && (trim($_POST["host"]) == "" || trim($_POST["port"]) == "" || trim($_POST["username"]) == "" || trim($_POST["host"]) == "")) {
			$errormessage = $_SWIFT["language"]["requiredfieldempty"];
		} else if (!ereg('^[[:alnum:]]+$', $_POST["prefix"]) && !empty($_POST["prefix"])) {
			$errormessage = $_SWIFT["language"]["invalidqueueprefix"];
		} else if ($_SWIFT["isdemo"] == true) {
			$errormessage = $_SWIFT["language"]["demomode"];
		} else {
			updateQueue($_emailqueue["emailqueueid"], strtolower($_POST["email"]), $_POST["tgroupid"], $_POST["departmentid"], $_POST["priorityid"], $_POST["ticketstatusid"], iif($_POST["type"]==MODULE_BUGS, MODULE_BUGS, MODULE_TICKETS), $_POST["fetchtype"], $_POST["host"], $_POST["port"], $_POST["username"], $_POST["password"], $_POST["customfromname"], $_POST["customfromemail"], $_POST["queuesignature"], iif($_POST["registrationrequired"]==1, true, false), iif($_POST["ticketautoresponder"]==1, true, false), iif($_POST["replyautoresponder"]==1, true, false), $_POST["prefix"]);

			printRedirect(sprintf($_SWIFT["language"]["queueupdconfirm"], htmlspecialchars($_POST["email"])), "index.php?_m=parser&_a=manageemailqueues&updatequeueid=".intval($_emailqueue["emailqueueid"]));

			exit;
		}
	}

	$_POST = array_merge($_POST, $_emailqueue);

	$interface->adminHeader($_SWIFT["language"]["mailparser"]." > ".$_SWIFT["language"]["editemailqueue"], 1);

	$interface->adminNavBar('<a href="index.php?_m=parser&_a=manageemailqueues" title="'.$_SWIFT["language"]["emailqueues"].'">'.$_SWIFT["language"]["emailqueues"].'</a> &raquo; <a href="index.php?_m=parser&_a=editemailqueue&emailqueueid='. intval($_emailqueue["emailqueueid"]) .'" title="'.$_SWIFT["language"]["editemailqueue"].'">'.$_SWIFT["language"]["editemailqueue"].'</a>', $_SWIFT["language"]["desc_mailparser"] , 4);

	printInfoBox($infomessage);
	printErrorBox($errormessage);

	printFormStart("queueform");

	printMainTableHeader($_SWIFT["language"]["queuedetails"]);

	printDescRow($_SWIFT["language"]["emailgeneralfields"]);
	printTextRow("email", $_SWIFT["language"]["emailaddress"], $_SWIFT["language"]["desc_emailaddress"], "text", $_POST["email"]);

	$options = array();
	$options[0]["title"] = $_SWIFT["language"]["module_tickets"];
	$options[0]["value"] = MODULE_TICKETS;

	// Display only if bug tracking module is registered
	if ($module->isRegistered(MODULE_BUGS))
	{
		$options[1]["title"] = $_SWIFT["language"]["module_bugs"];
		$options[1]["value"] = MODULE_BUGS;
	}
	printSelectRow("type", $_SWIFT["language"]["emailtype"], $_SWIFT["language"]["desc_emailtype"], $options);
	unset($options);

	$options = array();
	$options[0]["title"] = $_SWIFT["language"]["fetchpipe"];
	$options[0]["value"] = "pipe";
	$options[0]["selected"] = true;
	$options[1]["title"] = $_SWIFT["language"]["fetchpop3"];
	$options[1]["value"] = "pop3";
	$options[2]["title"] = $_SWIFT["language"]["fetchpop3ssl"];
	$options[2]["value"] = "pop3ssl";
	$options[3]["title"] = $_SWIFT["language"]["fetchimap"];
	$options[3]["value"] = "imap";
	$options[4]["title"] = $_SWIFT["language"]["fetchimapssl"];
	$options[4]["value"] = "imapssl";
	printSelectRow("fetchtype", $_SWIFT["language"]["emailfetchtype"], $_SWIFT["language"]["desc_emailfetchtype"], $options, "switchFields(this.value);");
	unset($options);

	$_options = array();
	$index = 0;
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."templategroups` ORDER BY `tgroupid` ASC;");
	while ($dbCore->nextRecord())
	{
		$_options[$index]["title"] = $dbCore->Record["title"];
		$_options[$index]["value"] = $dbCore->Record["tgroupid"];
		if ($_POST["tgroupid"] == $dbCore->Record["tgroupid"])
		{
			$_options[$index]["selected"] = true;
		}
		$index++;
	}
	printSelectRow("tgroupid", $_SWIFT["language"]["templategroup"], $_SWIFT["language"]["desc_templategroup"], $_options);
	unset($_options);

	printDescRow($_SWIFT["language"]["emailimapfields"]);
	printTextRow("host", $_SWIFT["language"]["emailhost"], $_SWIFT["language"]["desc_emailhost"], "text", $_POST["host"]);
	printTextRow("port", $_SWIFT["language"]["emailport"], $_SWIFT["language"]["desc_emailport"], "text", $_POST["port"], "5");
	printTextRow("username", $_SWIFT["language"]["emailusername"], $_SWIFT["language"]["desc_emailusername"], "text", $_POST["username"], "20");
	printTextRow("password", $_SWIFT["language"]["emailpassword"], $_SWIFT["language"]["desc_emailpassword"], "password", $_POST["userpassword"], "20");

	?>
	<script language="Javascript">
		if (document.queueform.fetchtype.value == "pipe")
		{
			switchFields("pipe");
		}

		function switchFields(fieldtype)
		{
			if (fieldtype == "pipe")
			{
				document.queueform.host.value = "";
				document.queueform.port.value = "";
				document.queueform.username.value = "";
				document.queueform.password.value = "";

				disableField(document.queueform.host);
				disableField(document.queueform.port);
				disableField(document.queueform.username);
				disableField(document.queueform.password);
			} else {
				enableField(document.queueform.host);
				enableField(document.queueform.port);
				enableField(document.queueform.username);
				enableField(document.queueform.password);
			}

			if (fieldtype == "pop3")
			{
				document.queueform.port.value = "110";
			} else if (fieldtype == "imap") {
				document.queueform.port.value = "143";
			} else if (fieldtype == "pop3ssl") {
				document.queueform.port.value = "995";
			} else if (fieldtype == "imapssl") {
				document.queueform.port.value = "993";
			}
		}
	</script>
	<?

	printDescRow($_SWIFT["language"]["queueoverrides"]);
	printTextRow("customfromname", $_SWIFT["language"]["queuefromname"], $_SWIFT["language"]["desc_queuefromname"], "text", $_POST["customfromname"]);
	printTextRow("customfromemail", $_SWIFT["language"]["queuefromemail"], $_SWIFT["language"]["desc_queuefromemail"], "text", $_POST["customfromemail"]);

	printDescRow($_SWIFT["language"]["queuesettings"]);

	printTextRow("prefix", $_SWIFT["language"]["queueprefix"], $_SWIFT["language"]["desc_queueprefix"], "text", $_POST["prefix"]);
	printTextareaRow("queuesignature", $_SWIFT["language"]["queuesignature"], $_SWIFT["language"]["desc_queuesignature"], $_POST["contents"], "50");
	printYesNoRow("registrationrequired", $_SWIFT["language"]["registrationrequired"], $_SWIFT["language"]["desc_registrationrequired"], false);
	printYesNoRow("ticketautoresponder", $_SWIFT["language"]["issueautoresponder"], $_SWIFT["language"]["desc_issueautoresponder"], true);
//	printYesNoRow("replyautoresponder", $_SWIFT["language"]["replyautoresponder"], $_SWIFT["language"]["desc_replyautoresponder"], false);

	printDescRow($_SWIFT["language"]["ticketfields"]);
	// departments
	$options = array();
	$index = 0;
	foreach ($_SWIFT["departmentcache"] as $key=>$val)
	{
		if ($val["departmentmodule"] == "tickets")
		{
			$options[$index]["title"] = $val["title"];
			$options[$index]["value"] = $val["departmentid"];
			$index++;
		}
	}
	printSelectRow("departmentid", $_SWIFT["language"]["queuedepartment"], $_SWIFT["language"]["desc_queuedepartment"], $options);
	unset($options);

	// status
	$options = array();
	$index = 0;
	foreach ($_SWIFT["statuscache"] as $key=>$val)
	{
		$options[$index]["title"] = $val["title"];
		$options[$index]["value"] = $val["ticketstatusid"];
		$index++;
	}
	printSelectRow("ticketstatusid", $_SWIFT["language"]["queueticketstatus"], $_SWIFT["language"]["desc_queueticketstatus"], $options);
	unset($options);

	// priority
	$options = array();
	$index = 0;
	foreach ($_SWIFT["prioritycache"] as $key=>$val)
	{
		$options[$index]["title"] = $val["title"];
		$options[$index]["value"] = $val["priorityid"];
		$index++;
	}
	printSelectRow("priorityid", $_SWIFT["language"]["queuepriority"], $_SWIFT["language"]["desc_queuepriority"], $options);
	unset($options);

	printSubmitRow($_SWIFT["language"]["update"]);

	printMainTableFooter();

	addHiddenField("step", "1");
	addHiddenField("_m", "parser");
	addHiddenField("emailqueueid", $_emailqueue["emailqueueid"]);
	addHiddenField("_a", "editemailqueue");
	printFormEnd();

	$template->assign("backurl", "index.php?_m=parser&_a=manageemailqueues");

	$interface->adminFooter();









/**
* ###############################################
* MANAGE EMAIL QUEUES
* ###############################################
*/
} else if ($eventaction == "manageemailqueues") {
	if ($_GET["do"] == "delete" && $_GET["emailqueueid"] != "" && $_SWIFT["isdemo"] != true)
	{
		if (isset($_SWIFT["queuecache"]["list"][$_GET["emailqueueid"]]))
		{
			$infomessage = sprintf($_SWIFT["language"]["queuedeleteconfirm"], $_SWIFT["queuecache"]["list"][$_GET["emailqueueid"]]["email"]);
			deleteQueues(array($_GET["emailqueueid"]));
		}
	}

	if (trim($_REQUEST["insertqueueid"]) != "")
	{
		$infomessage = sprintf($_SWIFT["language"]["queueinsertconfirm"], $_SWIFT["queuecache"]["list"][$_REQUEST["insertqueueid"]]["email"]);
	} else if (trim($_REQUEST["updatequeueid"]) != "") {
		$infomessage = sprintf($_SWIFT["language"]["queueupdconfirm"], $_SWIFT["queuecache"]["list"][$_REQUEST["updatequeueid"]]["email"]);
	}

	$options["recordsperpage"] = "6";
	$options["sortby"] = "emailqueues.email";
	$options["sortorder"] = "asc";
	$options["massaction"][0]["title"] = $_SWIFT["language"]["delete"];
	$options["massaction"][0]["callback"] = "_maDeleteQueues";

	$options["idname"] = "emailqueueid";
	$options["quicksearch"] = true;

	$options["advancedsearch"][0]["title"] = $_SWIFT["language"]["emailaddress"];
	$options["advancedsearch"][0]["query"] = 'SELECT * FROM `'. TABLE_PREFIX .'emailqueues` AS emailqueues WHERE `email` LIKE \'%$_searchstr%\' $_sortjoin;';
	$options["advancedsearch"][1]["title"] = $_SWIFT["language"]["queuepriority"];
	$options["advancedsearch"][1]["query"] = 'SELECT * FROM `'. TABLE_PREFIX .'emailqueues` AS emailqueues LEFT JOIN `'. TABLE_PREFIX .'ticketpriorities` AS ticketpriorities ON (emailqueues.priorityid = ticketpriorities.priorityid) WHERE ticketpriorities.title LIKE \'%$_searchstr%\' $_sortjoin;';
	$options["advancedsearch"][2]["title"] = $_SWIFT["language"]["queueticketstatus"];
	$options["advancedsearch"][2]["query"] = 'SELECT * FROM `'. TABLE_PREFIX .'emailqueues` AS emailqueues LEFT JOIN `'. TABLE_PREFIX .'ticketstatus` AS ticketstatus ON (emailqueues.ticketstatusid = ticketstatus.ticketstatusid) WHERE ticketstatus.title LIKE \'%$_searchstr%\' $_sortjoin;';
	$options["advancedsearch"][3]["title"] = $_SWIFT["language"]["queuedepartment"];
	$options["advancedsearch"][3]["query"] = 'SELECT * FROM `'. TABLE_PREFIX .'emailqueues` AS emailqueues LEFT JOIN `'. TABLE_PREFIX .'departments` AS departments ON (emailqueues.departmentid = departments.departmentid) WHERE departments.title LIKE \'%$_searchstr%\' $_sortjoin;';
	$options["advancedsearch"][4]["title"] = $_SWIFT["language"]["emailhost"];
	$options["advancedsearch"][4]["query"] = 'SELECT * FROM `'. TABLE_PREFIX .'emailqueues` AS emailqueues WHERE `host` LIKE \'%$_searchstr%\' $_sortjoin;';

	$options["callback"] = "_queueFields";

	$options["toolbar"][0]["title"] = $_SWIFT["language"]["insertemailqueue"];
	$options["toolbar"][0]["url"] = "index.php?_m=parser&_a=insertemailqueue";

	$fields[0]["name"] = "emailqueues.email";
	$fields[0]["title"] = $_SWIFT["language"]["emailaddress"];
	$fields[0]["width"] = "";

	$fields[1]["name"] = "emailqueues.fetchtype";
	$fields[1]["title"] = $_SWIFT["language"]["emailfetchtype"];
	$fields[1]["width"] = "120";
	$fields[1]["align"] = "center";

	$fields[2]["name"] = "emailqueues.departmentid";
	$fields[2]["title"] = $_SWIFT["language"]["queuedepartment"];
	$fields[2]["width"] = "180";
	$fields[2]["align"] = "center";

	$fields[3]["name"] = "emailqueues.registrationrequired";
	$fields[3]["title"] = $_SWIFT["language"]["registrationrequired"];
	$fields[3]["width"] = "200";
	$fields[3]["align"] = "center";

	$fields[4]["type"] = "custom";
	$fields[4]["name"] = "options";
	$fields[4]["title"] = $_SWIFT["language"]["options"];
	$fields[4]["width"] = "120";
	$fields[4]["align"] = "center";

	$grid = new Grid();

	$interface->adminHeader($_SWIFT["language"]["mailparser"]." > ".$_SWIFT["language"]["manage"], 1);

	$interface->adminNavBar($_SWIFT["language"]["mailparser"], $_SWIFT["language"]["desc_mailparser"] , 4);
	printInfoBox($infomessage);

	$grid->start("emailqueue", $_SWIFT["language"]["queuelist"], 'SELECT * FROM `'. TABLE_PREFIX .'emailqueues` AS emailqueues $_sortjoin;', 'SELECT COUNT(*) AS totalitems FROM `'. TABLE_PREFIX .'emailqueues` AS emailqueues;', 'SELECT * FROM `'. TABLE_PREFIX .'emailqueues` AS emailqueues WHERE `email` LIKE \'%$_searchstr%\' $_sortjoin;', $fields, $options);
	$grid->display("emailqueue");
	
	$interface->adminFooter();







/**
* ###############################################
* PARSER LOG
* ###############################################
*/
} else if ($eventaction == "parserlog") {
	$options["recordsperpage"] = "12";
	$options["sortby"] = "parserlogs.dateline";
	$options["sortorder"] = "desc";
	$options["massaction"][0]["title"] = $_SWIFT["language"]["delete"];
	$options["massaction"][0]["callback"] = "_maDeleteParserlog";

	$options["idname"] = "parserlogid";
	$options["quicksearch"] = true;

	$options["advancedsearch"][0]["title"] = $_SWIFT["language"]["emailsubject"];
	$options["advancedsearch"][0]["query"] = 'SELECT * FROM `'. TABLE_PREFIX .'parserlogs` AS parserlogs WHERE parserlogs.subject LIKE \'%$_searchstr%\' $_sortjoin;';
	$options["advancedsearch"][1]["title"] = $_SWIFT["language"]["emailfrom"];
	$options["advancedsearch"][1]["query"] = 'SELECT * FROM `'. TABLE_PREFIX .'parserlogs` AS parserlogs WHERE parserlogs.fromemail LIKE \'%$_searchstr%\' $_sortjoin;';
	$options["advancedsearch"][2]["title"] = $_SWIFT["language"]["emailto"];
	$options["advancedsearch"][2]["query"] = 'SELECT * FROM `'. TABLE_PREFIX .'parserlogs` AS parserlogs WHERE parserlogs.toemail LIKE \'%$_searchstr%\' $_sortjoin;';
	$options["advancedsearch"][3]["title"] = $_SWIFT["language"]["emaildescription"];
	$options["advancedsearch"][3]["query"] = 'SELECT * FROM `'. TABLE_PREFIX .'parserlogs` AS parserlogs WHERE parserlogs.description LIKE \'%$_searchstr%\' $_sortjoin;';
	$options["advancedsearch"][4]["title"] = $_SWIFT["language"]["emailcontents"];
	$options["advancedsearch"][4]["query"] = 'SELECT * FROM `'. TABLE_PREFIX .'parserlogs` AS parserlogs LEFT JOIN `'. TABLE_PREFIX .'parserlogdata` AS parserlogdata ON (parserlogs.parserlogid = parserlogdata.parserlogid) WHERE parserlogdata.contents LIKE \'%$_searchstr%\' $_sortjoin;';

	$options["callback"] = "_parserLogFields";

	$fields[0]["name"] = "parserlogs.subject";
	$fields[0]["title"] = $_SWIFT["language"]["emailsubjectresult"];
	$fields[0]["width"] = "";

	$fields[1]["name"] = "parserlogs.logtype";
	$fields[1]["title"] = $_SWIFT["language"]["emailstatus"];
	$fields[1]["width"] = "120";
	$fields[1]["align"] = "center";

	$fields[2]["name"] = "parserlogs.dateline";
	$fields[2]["title"] = $_SWIFT["language"]["date"];
	$fields[2]["width"] = "170";
	$fields[2]["align"] = "center";

	$fields[3]["name"] = "parserlogs.parsetimetaken";
	$fields[3]["title"] = $_SWIFT["language"]["emailparsetime"];
	$fields[3]["width"] = "130";
	$fields[3]["align"] = "center";

	$grid = new Grid();

	$interface->adminHeader($_SWIFT["language"]["mailparser"]." > ".$_SWIFT["language"]["parserlog"], 1);

	$interface->adminNavBar('<a href="index.php?_m=parser&_a=manageemailqueues" title="'.$_SWIFT["language"]["mailparser"].'">'.$_SWIFT["language"]["mailparser"].'</a> &raquo; <a href="index.php?_m=parser&_a=parserlog" title="'.$_SWIFT["language"]["parserlogs"].'">'.$_SWIFT["language"]["parserlogs"].'</a>', $_SWIFT["language"]["desc_parserlog"] , 4);

	printInfoBox($infomessage);

	$grid->start("parserlog", $_SWIFT["language"]["parserlogs"], 'SELECT * FROM `'. TABLE_PREFIX .'parserlogs` AS parserlogs $_sortjoin;', 'SELECT COUNT(*) AS totalitems FROM `'. TABLE_PREFIX .'parserlogs` AS parserlogs;', 'SELECT * FROM `'. TABLE_PREFIX .'parserlogs` AS parserlogs WHERE `subject` LIKE \'%$_searchstr%\' $_sortjoin;', $fields, $options);
	$grid->display("parserlog");
	
	$interface->adminFooter();





/**
* ###############################################
* MANAGE BREAKLINES
* ###############################################
*/
} else if ($eventaction == "managebreaklines") {
	if ($_GET["deletebreakline"] == 1 && !empty($_GET["breaklineid"]) && $_SWIFT["isdemo"] != true)
	{
		deleteBreaklines(array($_GET["breaklineid"]));

		printRedirect($_SWIFT["language"]["breaklinedelconfirm"], "index.php?_m=parser&_a=managebreaklines&breaklinedelconfirm=1");
		exit;
	} else if ($_POST["insertbreakline"] == 1 && $_SWIFT["isdemo"] != true) {
		if (trim($_POST["breakline"]) == "")
		{
			$errormessage = $_SWIFT["language"]["requiredfieldempty"];
		} else {
			insertBreakline($_POST["breakline"]);

			printRedirect($_SWIFT["language"]["breaklineinsertconfirm"], "index.php?_m=parser&_a=managebreaklines&breaklineinsertconfirm=1");
			exit;
		}
	}
	

	if (!empty($_GET["breaklinedelconfirm"]))
	{
		$infomessage = $_SWIFT["language"]["breaklinedelconfirm"];
	} else if (!empty($_GET["breaklineinsertconfirm"])) {
		$infomessage = $_SWIFT["language"]["breaklineinsertconfirm"];
	}
	

	$options["recordsperpage"] = "10";
	$options["sortby"] = "breakline";
	$options["sortorder"] = "asc";
	$options["massaction"][0]["title"] = $_SWIFT["language"]["delete"];
	$options["massaction"][0]["callback"] = "_maDeleteBreaklines";

	$options["idname"] = "breaklineid";
	$options["quicksearch"] = true;

	$options["advancedsearch"][0]["title"] = $_SWIFT["language"]["title"];
	$options["advancedsearch"][0]["query"] = 'SELECT * FROM `'. TABLE_PREFIX .'breaklines` WHERE `breakline` LIKE \'%$_searchstr%\' $_sortjoin;';

	$options["callback"] = "_breaklineFields";

	$options["toolbar"][0]["title"] = $_SWIFT["language"]["insert"];
	$options["toolbar"][0]["url"] = "javascript:switchDisplay('insertbreakline');";

	$fields[0]["name"] = "breakline";
	$fields[0]["title"] = $_SWIFT["language"]["title"];
	$fields[0]["width"] = "";

	$fields[1]["type"] = "custom";
	$fields[1]["name"] = "options";
	$fields[1]["title"] = $_SWIFT["language"]["options"];
	$fields[1]["width"] = "120";
	$fields[1]["align"] = "center";

	$grid = new Grid();

	$interface->adminHeader($_SWIFT["language"]["mailparser"]." > ".$_SWIFT["language"]["breaklines"], 1);

	$interface->adminNavBar('<a href="index.php?_m=parser&_a=manageemailqueues" title="'.$_SWIFT["language"]["mailparser"].'">'.$_SWIFT["language"]["mailparser"].'</a> &raquo; <a href="index.php?_m=parser&_a=managebreaklines" title="'.$_SWIFT["language"]["breaklines"].'">'.$_SWIFT["language"]["breaklines"].'</a>', $_SWIFT["language"]["desc_breaklines"] , 4);
	printInfoBox($infomessage);

	// ======= INSERT BREAKLINE =======
	echo '<div id="insertbreakline" style="DISPLAY:none;">'.SWIFT_CRLF;
	printFormStart();
	printMainTableHeader($_SWIFT["language"]["insertbreakline"]);

	printTextRow("breakline", $_SWIFT["language"]["breakline"], $_SWIFT["language"]["desc_breakline"], "text", $_POST["breakline"]);

	printSubmitRow($_SWIFT["language"]["insert"]);

	printMainTableFooter();
	addHiddenField("_m", "parser");
	addHiddenField("_a", "managebreaklines");
	addHiddenField("insertbreakline", "1");
	printFormEnd();
	echo '<BR /></div>'.SWIFT_CRLF;

	$grid->start("breaklines", $_SWIFT["language"]["breaklinelist"], 'SELECT * FROM `'. TABLE_PREFIX .'breaklines` $_sortjoin;', 'SELECT COUNT(*) AS totalitems FROM `'. TABLE_PREFIX .'breaklines`;', 'SELECT * FROM `'. TABLE_PREFIX .'breaklines` WHERE `breakline` LIKE \'%$_searchstr%\' $_sortjoin;', $fields, $options);
	$grid->display("breaklines");
	
	$interface->adminFooter();









/**
* ###############################################
* VIEW PARSER LOG
* ###############################################
*/
} else if ($eventaction == "viewparserlog") {
	if ($_POST["step"] == 1)
	{
		$_parserlog = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."parserlogs` AS parserlogs LEFT JOIN `". TABLE_PREFIX ."parserlogdata` AS parserlogdata ON (parserlogs.parserlogid = parserlogdata.parserlogid) WHERE parserlogs.parserlogid = '". intval($_POST["parserlogid"]) ."';");

		if (!empty($_parserlog["parserlogid"]))
		{
			$_mime = unserialize($_parserlog["contents"]);
			if ($_mime["mimedata"] != $_SWIFT["language"]["clearedduelimit"] && !empty($_mime["mimedata"]))
			{
				define("INPARSER", "1");

				$template->loadLanguageSection("emailparser");
				$template->loadLanguageSection("staff_tickets");
				$template->loadLanguageSection("tickets_auditlogs");
				require_once ("./includes/functions_mime.php");
				require_once ("./includes/functions_users.php");

				$_SWIFT["startparser"] = fetchmicrotime();

				if ($module->isRegistered(MODULE_TICKETS))
				{
					require_once ("./modules/tickets/functions_ticketcore.php");
					require_once ("./modules/tickets/functions_ticketmain.php");
					require_once ("./modules/tickets/functions_alertrules.php");
					require_once ("./modules/tickets/functions_attachments.php");
					require_once ("./modules/tickets/functions_search.php");
					require_once ("./modules/tickets/functions_sla.php");
				}
				require_once ("./modules/parser/functions_parsercore.php");
				require_once ("./modules/parser/functions_parserrules.php");
				
				parseRawMimeData($_mime["mimedata"]);

				echo $template->displayTemplate("header.tpl");
				echo '<body onLoad="javascript:reloadOpener();">';
				?>
				<script language="Javascript">
				function reloadOpener()
				{
					if (window.opener)
					{
						window.opener.location.reload(true);
					}
					window.close();
				}
				</script>
				<?
				echo $template->displayTemplate("footer.tpl");
			}
		}

	}

	viewParserLog($_REQUEST["parserlogid"]);

}

?>